<?php
/**
 * @package PHPKit.
 * @author: mawenpei
 * @date: 2016/11/28
 * @time: 11:30
 */
namespace HuoKit\HuoServer;

use HuoKit\HuoServer\Network\ServerFactory;
use swoole_process;
use HuoKit\HuoServer\Core\PidManager;
use HuoKit\HuoServer\Log\Logger;
use HuoKit\HuoServer\Core\Di;
use HuoKit\HuoServer\Core\Container;

class Daemon
{
    protected  $config;
    protected $logger;
    protected $pidManager;

    protected $master_process_name = 'huoserver:master';

    protected $workers;

    public function __construct($config)
    {
        $this->config = $config;
        $this->pidManager = new PidManager($this->config['pid_path']);
        if(isset($this->config['logger'])){
            $this->logger = $this->config['logger'];
        }else{
            $this->logger = new Logger(['log_path'=>$this->config['log_path']]);
        }
        Di::resolveFacadeInstance(new Container());
    }

    public function start()
    {
        if($this->pidManager->getMasterPid()){
            echo 'Error:HuoServer is already running' . "\r\n";
            return;
        }
        echo 'HuoServer is started' . "\r\n";

        $this->createHttpServer();

    }

    public function stop()
    {
        $pid = $this->pidManager->getMasterPid();
        if (empty($pid)) {
            echo "HuoServer is not running...\n";
            return ;
        }

        swoole_process::kill($pid,SIGTERM);
        $this->pidManager->clear();
        echo "HuoServer is stoped\n";
    }

    public function restart()
    {
        $this->stop();
        sleep(1);
        $this->start();
    }

    public function createHttpServer()
    {
        ServerFactory::createHttpServer($this->config)->setLogger($this->logger)->start();
    }
}